package com.chinasoft.bigdatadisplay.utils;


import com.chinasoft.bigdatadisplay.config.RemoteServerProperties;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class SshExecutor {

    @Autowired
    private RemoteServerProperties remoteServerProperties;

    /**
     * 执行远程命令
     * @param command 要执行的命令
     * @return 命令执行结果
     * @throws Exception 执行异常
     */
    public String executeCommand(String command) throws Exception {
        Session session = null;
        ChannelExec channel = null;
        try {
            // 1. 创建JSch对象
            JSch jsch = new JSch();

            // 2. 建立SSH会话
            session = jsch.getSession(
                    remoteServerProperties.getUsername(),
                    remoteServerProperties.getHost(),
                    remoteServerProperties.getPort()
            );
            session.setPassword(remoteServerProperties.getPassword());

            // 3. 跳过主机密钥检查（生产环境建议配置密钥认证）
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            // 4. 打开执行通道
            channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand(command);

            // 5. 获取命令输出
            try (InputStream in = channel.getInputStream()) {
                channel.connect();
                byte[] buffer = new byte[1024];
                StringBuilder result = new StringBuilder();
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    result.append(new String(buffer, 0, bytesRead, StandardCharsets.UTF_8));
                }
                return result.toString();
            }
        } catch (Exception e) {
            log.error("远程命令执行失败", e);
            throw e;
        } finally {
            // 6. 关闭资源
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }
}